var $szoaFileUtils = {
    //从JSP页面动态注入url值
//	fileServiceUrl:'http://10.248.71.211:7001',
	formatFileSize:function(bytes) {
		if (bytes === 0) return '0 B';
		var k = 1024;
		sizes = ['B','KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
		i = Math.floor(Math.log(bytes) / Math.log(k));
		var num = bytes / Math.pow(k, i);
		return num.toPrecision(3) + ' ' + sizes[i]; 
		//return (bytes / Math.pow(k, i)) + ' ' + sizes[i]; 
		//toPrecision(3) 后面保留一位小数，如1.0GB //return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
	},
	formatFileType:function(type) {
		return type;
	}
	
}

var fileServiceUrl='http://10.248.71.211:7001';

    var webUploader=new Array();
	$szoaFileUtils.uploadUrl = fileServiceUrl + '/file/uploadDfs',
	$szoaFileUtils.downloadUrl = fileServiceUrl + '/file/download',

        (function($) {

            $.fn.extend({
                // 文件上传
                szoaUploader: function(options) {
            		$szoaUploader = $(this);
                    var settings = {
                        url: $szoaFileUtils.uploadUrl,
                        fileType: "none",
                        fileName: "file",
                        data: {},
                        swf: '/common/fileUpLoad/js/Uploader.swf',
                        maxSize: 100,
                        extensions: null,
                        before: null,
                        complete: null,
                        onAllComplete: function (event) { }, // 当所有file都上传后执行的回调函数
                        fileNumLimit: null,//验证文件总数量, 超出则不允许加入队列
                        fileSizeLimit: null,//验证文件总大小是否超出限制, 超出则不允许加入队列。
                        fileSingleSizeLimit: null,//验证单个文件大小是否超出限制, 超出则不允许加入队列
                        PostbackHold: false,
                        auto:false
                    };
                    $.extend(settings, options);
                    alert(settings.moduleName);
                    settings.extensions = 'txt,jpg,jpeg,bmp,gif,png,zip,rar,7z,doc,docx,xls,xlsx,ppt,pptx,pdf,swf,flv,mp3,wav,avi,rm,rmvb';
                    var $hiddenInput = $('#UploadhiddenInput');
                        var element = this;
                        var $element = $(element);
                        var webUploader;

                    WebUploader.Uploader.register({
                        "before-send-file":"beforeSendFile"
                    },{
                        beforeSendFile: function(file,formData){

                            var task = new $.Deferred();

                            webUploader.md5File(file,0,15*1024*1024).then(function(val){
                                $.ajax({
                                    type: "GET"
                                    , url: 'http://10.248.71.211:7001/file/md5CheckUpload'
                                    , data: {
                                        md5: val,fileSize:file.size,userId:settings.userId,moduleName:settings.moduleName,fileSrcName:file.name  //后台接收 String md5
                                    }
                                    , cache: false
                                    , timeout: 3000
                                    , dataType: "json"
                                }).then(function(data, textStatus, jqXHR){
                                    if(data.message==0){   //若存在，这返回失败给WebUploader，(后台操作)表明该文件不需要上传，然后就可以把数据库查询出的文件信息的物理路径给新文件
                                        task.reject(); //
                                        webUploader.skipFile(file);
                                       // setTableBtn(file.id,'秒传');
                                       // element.progress(file.id, '100%');
                                        if(settings.onUploadSuccess){
                                            if (typeof settings.onUploadSuccess == "function") {
                                                settings.onUploadSuccess(file, data);
                                            }
                                        }
                                        $("#hiddenInput" + $(item)[0].id + file.id).val(data.url);
                                    }else{
                                        webUploader.options.formData={md5:val,fileSize:file.size,userId:settings.userId,moduleName:settings.moduleName};
                                        task.resolve();
                                    }
                                }, function(jqXHR, textStatus, errorThrown){
                                    //任何形式的验证失败，都触发重新上传
                                    task.resolve();
                                });
                            });
                            return $.when(task);
                        }
                    });

                    webUploader = WebUploader.create({
                            server: settings.url + (settings.url.indexOf('?') < 0 ? '?' : '&') + 'fileType=' + settings.userId + '&token='+settings.moduleName,
                            //如果单个文件自动上传 在传参是建议把multiple设置成false禁止多选文件
                            pick: {
                                id: element,
                                multiple: true
                            },
                        	swf: '/common/fileUpLoad/js/Uploader.swf',
                            fileVal: settings.fileName,
                            formData: settings.data,
                            fileSingleSizeLimit: settings.maxSize * 1024 * 1024,
                            accept: {
                                extensions: settings.extensions
                            },
                           //如果单个文件自动上传 在传参阶段是建议把fileNumLimit设置成1即文件队列里只能有一个待上传文件
                            fileNumLimit: 10,
                            auto:settings.auto,
                            resize: false,
                        }).on('beforeFileQueued', function(file) {
                            if ($.isFunction(settings.before) && settings.before.call(element, file) === false) {
                                return false;
                            }
                            if (settings.extensions == ''|| file.ext == '') {
                                this.trigger('error', 'Q_TYPE_DENIED');
                                return false;
                            }
                            //this.reset();

                            //console.log($element.parent("div").prev("div").attr("class"));
                            //$progressBar.show();
                        }).on( 'fileQueued', function( file ) {
							//【lei】  在这里选择文件之后
                        	//文件选择成功后的回调函数
                            if(settings.onFileQueued){
							    if (typeof settings.onFileQueued == "function") {
						       		settings.onFileQueued(file)
                            	}
                            }
                            //自动上传
                            if(settings.auto == true){
                            	this.upload();
                            }
                            
                        }).on('uploadProgress', function(file, percentage) {
							//【lei】进度条
//                        	var $li = $('#' + $element.attr('id').substring(0,8) + file.id),
//
//                            $percent = $li.find('.progress .bar');
//	                        //$li.find('.progress .bar').html('上传中');
//	                        $li.find(".progress .percentage .text").text(Math.round(percentage * 100) + '%');
//	                        $percent.css('width', percentage * 100 + '%');
	                        
                        	//文件选择成功后的回调函数
                            if(settings.onUploadProgress){
							    if (typeof settings.onUploadProgress == "function") {
						       		settings.onUploadProgress(file, percentage);
                            	}
                            }
                        }).on('uploadAccept', function(file, data) {
                            // $progressBar.fadeOut("slow", function() {
                            //     $progressBar.width(0);
                            // });
                            // if (data.message.type != 'success') {
                            //     alert(data.message);
                            //     return false;
                            // }
                            if ($.isFunction(settings.complete)) {
                                settings.complete.call(element, file, data);
                            }
                        }).on('uploadSuccess', function(file, data) {
                        	//【lei】 上传成功回调放法
                        	
                        	//文件选择成功后的回调函数
                            if(settings.onUploadSuccess){
							    if (typeof settings.onUploadSuccess == "function") {
						       		settings.onUploadSuccess(file, data);
                            	}
                            }
                        }).on('fileDequeued', function (file) {

                        	//=====================================================
                        var fullName = $("#hiddenInput" + $element.attr('id').substring(0,8) + file.id).val();
                        // if (fullName!=null) {删除服务器文件
                        //     $.post(webuploaderoptions.deleteServer, { fullName: fullName }, function (data) {
                        //         alert(data.message);
                        //     })
                        // }
                        $("#"+ $element.attr('id').substring(0,8) + file.id).remove();
                        $("#hiddenInput" + $element.attr('id').substring(0,8) + file.id).remove();
                        	//=====================================================

                           }).on('error', function(type) {
                            switch(type) {
                                case "F_EXCEED_SIZE":
                                    alert("warn上传文件大小超出限制");
                                    break;
                                case "Q_TYPE_DENIED":
                                    alert("warn上传文件格式不正确");
                                    break;
                                default:
                                    alert("warn上传文件出现错误");
                                    alert(type);
                            }
                        });
                   
                    $szoaUploader.opts = settings;
                    //删除文件
                    $szoaUploader.removeFile = function(fileId){
//                        var file = settings.webUploader.getFile(id);
                    	webUploader.removeFile(fileId);
                    }
                    
                    //文件提交
                    $szoaUploader.upload = function(){
	                    	return webUploader.upload();
	                };
                    
                    return $szoaUploader;


                }

            });

        })(jQuery);